package com.gmics.unifiq;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.SimpleAdapter;

import com.gmics.android.R;
import com.gmics.unifiq.controller.GooglePlace;
import com.gmics.unifiq.entity.Place;
import com.gmics.unifiq.entity.PlaceDetails;
import com.gmics.unifiq.entity.PlaceList;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class ViewMap extends Activity {
	private GoogleMap viewMap;
	private final LatLng SINGAPORE = new LatLng(1.368123, 103.798981);
	private final LatLng YISHUN = new LatLng(1.4301694,103.8369485);
	private int locationIcon = R.drawable.map_pin;
	private Button submitBtn;
	private String locationRef = null, locationName = null, snippet;
	private Marker areaMarker;
	private GooglePlace googlePlace = new GooglePlace();
	private PlaceList locationList;
	private PlaceDetails locationDetails;
	private ArrayList<PlaceDetails> locationArr = new ArrayList<PlaceDetails>();
	private String[] locationACArr, example = {"A", "B", "C"}, locationTypeArr;
	private AutoCompleteTextView locationACTV;
	private ProgressDialog pDialog;
	public static int RESULT_FAIL = 2;
	public static String KEY_REFERENCE = "reference"; // id of the place
	public static String KEY_NAME = "name"; // name of the place
	private ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String, String>>();
	
	private Bundle bundle;
	
    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_map_layout);
		bundle = getIntent().getExtras();
		
		ArrayList<PlaceDetails> tempLocationArr = (ArrayList<PlaceDetails>) bundle.getSerializable("locationArr");
		ArrayList<HashMap<String, String>> tempPlacesListItems = (ArrayList<HashMap<String, String>>) bundle.getSerializable("placesListItems");
		
		if (tempLocationArr != null && tempPlacesListItems != null){
			locationArr = tempLocationArr;
			placesListItems = tempPlacesListItems;
		}
		
		locationTypeArr = getResources().getStringArray(R.array.location_type);
		
		new LoadMap().execute();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	class LoadMap extends AsyncTask<String, String, String> {
		 
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ViewMap.this);
            pDialog.setMessage("Loading map...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        
        @Override
		protected String doInBackground(String... args) {
    		try {
    			if (locationArr.size() == 0 && placesListItems.size() == 0){
	    			locationList = googlePlace.radarSearch(locationTypeArr);
	    			for (Place p : locationList.results) {
	    				locationArr.add(googlePlace.getPlaceDetails(p.reference));
	    			}
	    					
	    			locationACArr = new String[locationArr.size()];
	    			for (int i = 0; i < locationArr.size(); i++){
	    				locationACArr[i] = locationArr.get(i).result.name;
						HashMap<String, String> map = new HashMap<String, String>();
	
						map.put(KEY_REFERENCE, locationArr.get(i).result.reference);
						map.put(KEY_NAME, locationArr.get(i).result.name);
	
						placesListItems.add(map);
	    			}
    			}
    		} catch (Exception e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
            return null;
        }

        @Override
		protected void onPostExecute(String file_url) {
            pDialog.dismiss();
            runOnUiThread(new Runnable() {
                @Override
				public void run() {
            		
            		submitBtn = (Button) findViewById(R.id.submit_btn);
            		locationACTV = (AutoCompleteTextView) findViewById(R.id.location_actv);
            		
            		try{
            			locationRef = bundle.getString("locationRef");
            			locationDetails = googlePlace.getPlaceDetails(locationRef);
            		}
            		catch (Exception e){
            		}
            		
            		LatLng area = new LatLng(locationDetails.result.geometry.location.lat, locationDetails.result.geometry.location.lng);
            		
            		viewMap = ((MapFragment) getFragmentManager().findFragmentById(
            				R.id.view_map)).getMap();
            		viewMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            		viewMap.moveCamera(CameraUpdateFactory.newLatLngZoom(area, 12f));
            		

            		areaMarker = viewMap.addMarker(new MarkerOptions().position(area)
            				.title(locationDetails.result.name).snippet(locationDetails.result.formatted_address)
            				.icon(BitmapDescriptorFactory.fromResource(locationIcon)));
            		
            		submitBtn.setOnClickListener(new OnClickListener(){

						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							onBackPressed();
						}
            			
            		});
            		
					SimpleAdapter locationAdapter = new SimpleAdapter(ViewMap.this,
							placesListItems, R.layout.location_list_item,
							new String[] { KEY_REFERENCE, KEY_NAME }, new int[] {
									R.id.location_ref, R.id.location_tv });
					
            		//ArrayAdapter<CharSequence> locationAdapter = new ArrayAdapter<CharSequence>(ViewMap.this, android.R.layout.select_dialog_item, locationACArr);
            		locationACTV.setThreshold(1);
            		locationACTV.setAdapter(locationAdapter);
            		
            		locationACTV.setOnItemClickListener(new OnItemClickListener(){
						@Override
						public void onItemClick(AdapterView<?> adapterView, View v,
								int pos, long id) {
							// TODO Auto-generated method stub
							int selectedPos = 0;
							HashMap<String, String> map = (HashMap<String, String>) adapterView.getItemAtPosition(pos);
							for (int i = 0; i < placesListItems.size(); i++){
								if (map.get(KEY_REFERENCE).equals(locationArr.get(i).result.reference)){
									selectedPos = i;
									break;
								}
							}
		
							String title = locationArr.get(selectedPos).result.name;
							String address = locationArr.get(selectedPos).result.formatted_address;
							LatLng area = new LatLng(locationArr.get(selectedPos).result.geometry.location.lat, locationArr.get(selectedPos).result.geometry.location.lng);
							
							Log.d("title", title);
							
							viewMap.moveCamera(CameraUpdateFactory.newLatLngZoom(area, 12f));
	          				areaMarker.setTitle(title);
	          				areaMarker.setSnippet(address);
            				areaMarker.setPosition(area);
            				
    						locationACTV.setText(title);
            				locationName = title;
            				locationRef = locationArr.get(selectedPos).result.reference;

						}
            			
            		});
            		
            		
                }
            });
            
        }

 
    }


	@Override
	public void onBackPressed() {
		int result = 0;
		Bundle b = new Bundle();
		b.putSerializable("locationArr", locationArr);
		b.putSerializable("placesListItems", placesListItems);
		Intent plannerScreen = new Intent(this, Planner.class);
		
		if (locationName != null){
			plannerScreen.putExtra("locationName", locationName);
			plannerScreen.putExtra("locationRef", locationRef);
			plannerScreen.putExtras(b);
	    	result = RESULT_OK;
		}
		else{
			result = RESULT_FAIL;
		}
		
		setResult(result, plannerScreen);
		super.onBackPressed();
	}


}
